import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * create by yongli on 2020-05-05 22:49
 */

public class ChannelServerMain {

    // 使用基于SocketChannel的通信方法
    public static void main2(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 获取一个实例
        serverSocketChannel.bind(new InetSocketAddress(7070));
        // ServerSocket socket = serverSocketChannel.socket();
        serverSocketChannel.configureBlocking(false); // 非阻塞
        System.out.println("the server start");

        while (true) {
            // 获得一个连接,accept方法也变成异步了
            SocketChannel socketChannel = serverSocketChannel.accept();

            // while(socketChannel!=null)一直没有退出正循环，所以无法接受新的请求
            // 也依赖于下面的快速处理完一个请求
            if (socketChannel != null) {
                // 获得的连接也要设置为非阻塞
                socketChannel.configureBlocking(false);
                System.out.println("this is blocking：" + socketChannel.isBlocking());
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                System.out.println("process the input, but no data before");

                // 直接就返回了
                // 如果没有立马发数据，就会导致收不到数据
                // 一个核心问题就是什么时候真正可读？这是就需要注册到一个选择器中
                int i = socketChannel.read(byteBuffer);
                System.out.println("process the input, but no data after" + i);
                byteBuffer.flip(); // 翻转，拥有重新读取
                String str = new String(byteBuffer.array());
                System.out.println(str);
            }
        }

    }
}
